(function() {
    'use strict';
    angular.module('app')
        .factory('ServerErrorHandler', ['$q', '$filter', 'logger', ServerErrorHandler]);

    function ServerErrorHandler ($q, $filter, logger) {

        var onRequest = function(config) {
            var textMethods = config.method === "POST" || config.method === "PUT";
            var jsonMethods = config.method === "DELETE";

            if(textMethods) {
                if (!config.headers["Content-Type"]) {
                    config.headers["Content-Type"] = "text/plain";
                }
            }
            if(jsonMethods) {
                if (!config.headers["Content-Type"]) {
                    config.headers["Content-Type"] = "application/json";
                }
            }

            return config;
        };

        var onResponse = function (response) {
            //console.log('onResponse', response);
            return response;
        };

        var onResponseError = function (rejection) {
            var textKey = 'GENERIC_AJAX_ERROR_CODE_UNHANDLED';

            switch (rejection.status) {
                case 400:
                    textKey = 'GENERIC_AJAX_ERROR_CODE_400';
                break;

                case 404:
                    textKey = 'GENERIC_AJAX_ERROR_CODE_404';
                break;

                case 500:
                    textKey = 'GENERIC_AJAX_ERROR_CODE_500';
                break;
            }

            logger.logError($filter('translate')(textKey));

            return $q.reject(rejection);
        };
    
        return {
            'request': onRequest,
            'response': onResponse,
            'responseError': onResponseError
        };
    }
    
})();